package com.huanbao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huanbao.base.dto.UserDailyInspectDTO;
import com.huanbao.entity.CheckResult;
import com.huanbao.entity.DailyDeliveryRecord;
import com.huanbao.entity.PersonalNotification;
import com.huanbao.mapper.CheckResultMapper;
import com.huanbao.mapper.DailyDeliveryRecordMapper;
import com.huanbao.mapper.PersonalNotificationMapper;
import com.huanbao.mapper.ScheduledTaskMapper;
import com.huanbao.service.ScheduledTaskService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @description:
 * @author: ZQ
 * @date: 2021-05-08-10:02
 */
@Service
public class ScheduledTaskServiceImpl implements ScheduledTaskService {

    @Resource
    private ScheduledTaskMapper scheduledTaskMapper;

    @Resource
    private DailyDeliveryRecordMapper dailyDeliveryRecordMapper;

    @Resource
    private PersonalNotificationMapper personalNotificationMapper;

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");


    @Override
    @Transactional
    public boolean dailyInspect() {
        try {
            List<UserDailyInspectDTO> dailyInspectDTOS = scheduledTaskMapper.dailyInspect();
            for (UserDailyInspectDTO dto : dailyInspectDTOS) {
                //判断每日投放是否更新
                if (dto.getUpdatedDt() != null) {
                    String format = dto.getUpdatedDt().format(formatter);
                    if (format.equals(LocalDateTime.now().format(formatter))) continue;
                }
                //持续天数改为0
                DailyDeliveryRecord one = dailyDeliveryRecordMapper.selectOne(new QueryWrapper<DailyDeliveryRecord>().eq("user_id", dto.getId()));
                if(null != one){
                    one.setContinusousDays(0);
                    dailyDeliveryRecordMapper.updateById(one);
                }
                //生成巡检报告
                PersonalNotification notification = new PersonalNotification();
                notification.setPublisher("系统每日巡检");
                notification.setContent(LocalDateTime.now().format(formatter) + "未投放。");
                notification.setUserId(dto.getId());
                personalNotificationMapper.insert(notification);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
